package com.infore.airsupervise.ui.fragment;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.animation.AnimationSet;
import com.amap.api.maps.model.animation.ScaleAnimation;
import com.beardedhen.androidbootstrap.AwesomeTextView;
import com.beardedhen.androidbootstrap.font.FontAwesome;
import com.infore.airsupervise.R;
import com.infore.airsupervise.app.AppInfo;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.app.MsgConst;
import com.infore.airsupervise.app.NaviManager;
import com.infore.airsupervise.app.StatusConst;
import com.infore.airsupervise.bean.AirStationE;
import com.infore.airsupervise.bean.UserE;
import com.infore.airsupervise.biz.StationMapShowBiz;
import com.infore.airsupervise.biz.UserLocationBiz;
import com.infore.airsupervise.biz.impl.StationMapShowBizImpl;
import com.infore.airsupervise.biz.impl.UserLocationBizImpl;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.other.listener.MainFragBtnClickListener;
import com.infore.airsupervise.ui.activity.NewAQIActivity;
import com.infore.airsupervise.ui.activity.PeresonRouteActivity;
import com.infore.airsupervise.ui.activity.PersonDetailActivity;
import com.infore.airsupervise.ui.widget.HorizontalSelectScrollView;
import com.infore.airsupervise.ui.widget.NaviDialog;
import com.infore.airsupervise.utils.AirLevelUtil;
import com.infore.airsupervise.utils.AmapUtil;
import com.infore.airsupervise.utils.JumpUtil;
import com.infore.airsupervise.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import info.hoang8f.android.segmented.SegmentedGroup;

/**
 * 地图 Fragment
 */
public class MapFragment extends BaseFragment
        implements AMap.OnMarkerClickListener,
        AMap.OnMapLoadedListener, AMapLocationListener {
    public static final String TAG = "MapFragment";

    @BindView(R.id.map_view)
    TextureMapView mapView;

    @BindView(R.id.titlebar_left_menu)
    AwesomeTextView titlebarLeftMenu;
    @BindView(R.id.titlebar_right_menu)
    AwesomeTextView titlebarRightMenu;
    @BindView(R.id.layout_titleBar)
    RelativeLayout layoutTitleBar;
    @BindView(R.id.segment_map)
    SegmentedGroup segmentMap;
    @BindView(R.id.iv_marker_label)
    ImageView ivMarkerLabel;
    @BindView(R.id.rg_marker_type)
    RadioGroup rgMarkerType;
    @BindView(R.id.iv_site_pick)
    ImageView ivSitePick;
    @BindView(R.id.tv_site_down)
    TextView tvSiteDown;
    @BindView(R.id.layout_site_type)
    LinearLayout layoutSiteType;
    @BindView(R.id.sv_factor)
    HorizontalSelectScrollView  svFactor;
    @BindView(R.id.layout_content_site_type)
    FrameLayout frameLayout;

    private static final float WINDOW_ALPHA_WHITE = 1.0f;
    private static final float WINDOW_ALPHA_NIGHT = 0.8f;

    private static final int  LABEL_ZG = 1; //直观
    private static final int LABEL_CG = 0; //常规
    private static final int DATA_USER = 1;
    private static final int DATA_STATION = 0;


    private View infoWindow = null;
    private View userWindow = null;
    private AMap aMap = null;
    private AMapLocationClient aMapClient = null;

    private String mnStr = "";

    private MainFragBtnClickListener listener;
    private StationMapShowBiz stationMapShowBiz = null;
    private UserLocationBiz locationBiz = null ;

    private int factor_type = StatusConst.AIR_TYPE_AQI;
    private int label_type = LABEL_CG;
    private int station_type = StatusConst.STATION_ALL;
    private int data_type = DATA_STATION;

    private List<AirStationE> siteList = new ArrayList<>();
    private List<Marker> markerList = new ArrayList<>();
    private List<UserE> userEList = new ArrayList<>() ;

    private boolean isFirst = true;
    private boolean fullScreen = false;
    private boolean isRefresh = false;

    private double lat;
    private double lnt;
    private String destination;

    // 地图比例
    private float zoom = 10.8f;

    private float windowAlpha = WINDOW_ALPHA_WHITE;
    private int mapType = AMap.MAP_TYPE_NORMAL;
    //动画
    private AlphaAnimation showAlphaAnim;
    private AlphaAnimation hideAlphaAnim;
    private TranslateAnimation showTransAnim;
    private TranslateAnimation hideTransAnim;
    private AnimationSet animationSet ;
    private boolean isDoAnim = true; //是否显示图例



    @Override
    public void onMapLoaded() {
        getStationData();
    }

    public MapFragment() {
    }

    @SuppressLint("ValidFragment")
    public MapFragment(MainFragBtnClickListener listener) {
        this.listener = listener;
    }

    @SuppressLint("ValidFragment")
    public MapFragment(String mnStr, MainFragBtnClickListener listener) {
        this.mnStr = mnStr;
        this.listener = listener;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_map, container, false);
        unbinder = ButterKnife.bind(this, view);
        stationMapShowBiz = new StationMapShowBizImpl();
        initView();
        initMap(savedInstanceState);
        Log.d(TAG, "onCreateView: ");
        return view;
    }

    private void initView() {
        // 判断显示用户/返回图标
        titlebarLeftMenu.setFontAwesomeIcon(
                mnStr.isEmpty() ? FontAwesome.FA_USER : FontAwesome.FA_CHEVRON_LEFT);
        titlebarRightMenu.setVisibility(View.INVISIBLE);
        //segment
        segmentMap.setOnCheckedChangeListener(checkedChangedListener);
        // 图例radiogroup
        rgMarkerType.setOnCheckedChangeListener(markerChangerListener);
        // 因子
        List<String> list_factor = Arrays.asList(getResources().getStringArray(R.array.airType));
        svFactor.setFactorList(list_factor);
        svFactor.setFactorChangerListener(factorChangerListener);
    }

    /**
     * 初始化地图
     */
    private void initMap(Bundle savedInstanceState) {
        //初始化地图控制器对象
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        UiSettings uiSettings = aMap.getUiSettings();
        uiSettings.setScaleControlsEnabled(true);
        uiSettings.setMyLocationButtonEnabled(false);
        uiSettings.setZoomControlsEnabled(false);
        uiSettings.setScaleControlsEnabled(false);

        aMap.setOnMapLoadedListener(this);
        aMap.setOnMarkerClickListener(this);
     //   aMap.setOnInfoWindowClickListener(this);
        aMap.setInfoWindowAdapter(infoWindowAdapter);
        // aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(22.885674, 113.177242), 12f));
        mapView.onCreate(savedInstanceState);
    }

    /**
     * 初始化定位
     */
    private void initLoacation() {
        if (null == aMapClient) {
            aMapClient = new AMapLocationClient(getContext());
            // 定位参数
            AMapLocationClientOption option = new AMapLocationClientOption();
            option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            aMapClient.setLocationOption(option);
            aMapClient.setLocationListener(this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mapView != null) {
            mapView.onDestroy();
        }
        // 销毁定位服务
        if (aMapClient != null) {
            aMapClient.stopLocation();
            aMapClient.onDestroy();
        }
        aMapClient = null;
        Log.d(TAG, "onDestroy: ");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "onDestroyView: ");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop: ");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: ");
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
        Log.d(TAG, "onResume: ");
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
        Log.d(TAG, "onPause: ");
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
        Log.d(TAG, "onSaveInstanceState: ");
    }


    @Override
    public boolean onMarkerClick(Marker marker) {
        if (marker.isInfoWindowShown()) {
            marker.hideInfoWindow();
        } else {
                aMap.animateCamera(CameraUpdateFactory.changeLatLng(marker.getPosition()));
                marker.showInfoWindow();
        }
        return true;
    }

    /**
     * 自定义站点infoWindow窗口
     */
    public void render(Marker marker, View view) {
        final AirStationE station = (AirStationE) marker.getObject();
        if(station == null){
            return ;
        }
        TextView name = (TextView) view.findViewById(R.id.station_name);
        TextView updateTime = (TextView) view.findViewById(R.id.update_time);
        TextView airLevel = (TextView) view.findViewById(R.id.air_level);
        TextView address = (TextView) view.findViewById(R.id.station_address);
        TextView navi = (TextView) view.findViewById(R.id.tv_Navi);
        TextView detail = (TextView) view.findViewById(R.id.tv_detail);
        AirStationE.AirLevel airLevel1 = station.getAirLevel();
        name.setText(station.getName());
        updateTime.setText(station.getTime());

        airLevel.setText(airLevel1.getLevelStr());
        airLevel.setTextColor(ContextCompat.getColor(getContext(), airLevel1.getColorRes()));
        address.setText(station.getAddress());
        navi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.showShort(getContext(), "定位中...");
                if (TextUtils.isEmpty(station.getName())) {
                    destination = "目的地";
                } else {
                    destination = station.getName();
                }
                lat = station.getLat();
                lnt = station.getLnt();
                initLoacation();
                aMapClient.startLocation();
            }
        });
        detail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JumpUtil.jumpFromTo(getContext(), NewAQIActivity.class, Constants.INTENT_STR_KEY, station.getMn());
            }
        });
    }

    /**
     * 自定义 人员infoWindow窗口
     * @param marker
     * @param view
     */
    private void userRender(Marker marker, View view){
        final UserE userE = (UserE) marker.getObject();
        if(userE ==null){
            return ;
        }
        TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
        TextView tv_phone = (TextView) view.findViewById(R.id.tv_phone);
        TextView tv_address = (TextView) view.findViewById(R.id.person_address);
        TextView tv_upTime = (TextView) view.findViewById(R.id.update_time);
        TextView tv_line = (TextView) view.findViewById(R.id.tv_line);
        TextView tv_info = (TextView) view.findViewById(R.id.tv_info);
        tv_name.setText(userE.getRealName());
        tv_phone.setText(userE.getPhone());
        tv_address.setText(userE.getAddress());
        tv_upTime.setText(userE.getUpDateTime());
        //历史踪迹
        tv_line.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JumpUtil.jumpFromTo(getContext(), PeresonRouteActivity.class,Constants.INTENT_STR_KEY, userE.getUserId());
            }
        });
        //人员详情
        tv_info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JumpUtil.jumpFromTo(getContext(), PersonDetailActivity.class,Constants.INTENT_OBJ_KEY, userE);
            }
        });
    }

    /**
     * InfoWindowAdapter
     */
    private AMap.InfoWindowAdapter infoWindowAdapter = new AMap.InfoWindowAdapter() {
        @Override
        public View getInfoWindow(Marker marker) {
            return null;
        }

        @Override
        public View getInfoContents(Marker marker) {
            if(data_type == DATA_STATION) {
                if (infoWindow == null) {
                    infoWindow = LayoutInflater.from(getContext()).inflate(
                            R.layout.layout_window_device, null);
                    if (mapType == AMap.MAP_TYPE_NIGHT) {
                        infoWindow.setAlpha(WINDOW_ALPHA_NIGHT);
                    }
                }
                render(marker, infoWindow);
                return infoWindow;
            }else{
                if(userWindow == null){
                    userWindow = LayoutInflater.from(getContext()).inflate(
                            R.layout.layout_window_person ,null
                    );
                }
                userRender(marker,userWindow);
                return userWindow;
            }
        }
    };

    /**
     * 缩放按钮
     *
     @OnClick(R.id.btn_zoom) void zoomBtnClick() {
     fullScreen = !fullScreen;

     if (fullScreen) {

     layoutTitleBar.setVisibility(View.GONE);
     } else {
     layoutTitleBar.setVisibility(View.VISIBLE);
     }

     if (listener != null) {
     listener.onZoomBtnClick(fullScreen);
     }
     }
     */

    /**
     * 获取站点列表信息
     */
    private void getStationData() {
        //loading dialog
        final SweetAlertDialog dialog = new SweetAlertDialog(getContext(), SweetAlertDialog.PROGRESS_TYPE)
                .setTitleText(MsgConst.HARD_LOADING)
                .setContentText(MsgConst.PLEASE_WAITING);
        dialog.setCancelable(false);
        dialog.show();
        if (aMap != null) {
            aMap.clear();
        }
        stationMapShowBiz.sendStationRealDetailRequest(new OnServerResponseListener<List<AirStationE>>() {
            @Override
            public void onSucceed(List<AirStationE> result, String desc) {
                // 解析地图中心点
//                MapPoint centerPoint = JSON.parseObject(pointJson, MapPoint.class);

                if (isRefresh) {
                    //刷新时清空集合数据
                    siteList.clear();
                    markerList.clear();
                }
                siteList.addAll(result);
                LatLngBounds.Builder builder = new LatLngBounds.Builder(); //地图可见区域
                for (AirStationE stationE : result) {
                    //添加站点经纬度对象到地图可见区域
                    builder.include(addStationMarker(stationE));
                    addStationMarker(stationE);
                }
                if (TextUtils.isEmpty(mnStr)) {
                    //设置地图显示
                    aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 32));
//                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(centerPoint.getLat(), centerPoint.getLng()), zoom ));
                }
                dialog.dismiss();
            }

            @Override
            public void onFailed(int errorCode, String title, String desc) {
                //dialog 错误 异常提示
                dialog.setTitleText(title)
                        .setContentText(desc)
                        .setConfirmText(MsgConst.I_SEE)
                        .changeAlertType(SweetAlertDialog.WARNING_TYPE);
            }
        });
    }

    /**
     * 获取人员位置信息
     */
    private void getPsonLocationData() {
        if (null == locationBiz) {
            locationBiz = new UserLocationBizImpl();
        }
        //loading dialog
        final SweetAlertDialog dialog = new SweetAlertDialog(getContext(), SweetAlertDialog.PROGRESS_TYPE)
                .setTitleText(MsgConst.HARD_LOADING)
                .setContentText(MsgConst.PLEASE_WAITING);
        dialog.setCancelable(false);
        dialog.show();
        if (null != aMap) {
            aMap.clear();
            markerList.clear();
            siteList.clear();
        }
        locationBiz.getPsonLocationRequest(UserE.getUserInfo().getUserId(), new OnServerResponseListener<List<UserE>>() {
            @Override
            public void onSucceed(List<UserE> result, String desc) {

                LatLngBounds.Builder builder = new LatLngBounds.Builder(); //地图可见区域
                for (UserE userE : result) {
                    //添加站点经纬度对象到地图可见区域
                      builder.include(addPsonMarker(userE));
                    //addPsonMarker(userE);
                }
                //设置地图显示
                 aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(),32));
               // aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(22.885674, 113.177242), 12f));
                dialog.dismiss();
            }

            @Override
            public void onFailed(int errorCode, String title, String desc) {
                //dialog 错误 异常提示
                dialog.setTitleText(title)
                        .setContentText(desc)
                        .setConfirmText(MsgConst.I_SEE)
                        .changeAlertType(SweetAlertDialog.WARNING_TYPE);
            }
        });
    }



    /**
     * 定位回调
     * @param aMapLocation
     */
    @Override
    public void onLocationChanged(final AMapLocation aMapLocation) {
        aMapClient.stopLocation();
        int code = aMapLocation.getErrorCode();
        if (code == 0) {
            //打开导航提示框
            NaviDialog dialog = new NaviDialog(getContext(), AppInfo.getMapApps(getContext()));
            dialog.setNaviClickListener(new NaviDialog.NaviClickListener() {
                @Override
                public void NaviAppsListener(String packageName) {
                    Intent it = new Intent(Intent.ACTION_VIEW);
                    Uri uri;
                    switch (packageName) {
                        case "com.baidu.BaiduMap": //百度
                            LatLng origin = NaviManager.BD_encrypt(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                            LatLng desLatLnt = NaviManager.BD_encrypt(lat, lnt);
                            uri = Uri.parse(NaviManager.
                                    getBaiduUri("我的位置", origin.latitude, origin.longitude, destination, desLatLnt.latitude, desLatLnt.longitude));
                            it.setData(uri);
                            startActivity(it);
                            break;
                        case "com.autonavi.minimap": //高德
                            it.setPackage(packageName);
                            uri = Uri.parse(NaviManager.getgaodeUri("扬尘监控", lat, lnt));
                            it.setData(uri);
                            startActivity(it);
                            break;
                    }
                }

                @Override
                public void NaviWebListener() {  //网页
                    LatLng origin = NaviManager.BD_encrypt(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                    LatLng desLatLnt = NaviManager.BD_encrypt(lat, lnt);
                    Intent it = new Intent(Intent.ACTION_VIEW);
                    Uri uri = Uri.parse(NaviManager.
                            getWebBaiduMapUri("我的位置", origin.latitude, origin.longitude, destination, desLatLnt.latitude, desLatLnt.longitude, getContext().getPackageName()));
                    it.setData(uri);
                    startActivity(it);
                }
            });
            dialog.getDialog().show();
        } else if (code == 4) {
            ToastUtil.showShort(getContext(), "网络异常，请检查网络设置");
        } else if (code == 12) {
            ToastUtil.showShort(getContext(), "缺少定位权限！请在设备设置中打开");
        } else if (code == 9) {
            ToastUtil.showShort(getContext(), "定位服务初始化失败，请重新定位");
        } else {
            ToastUtil.showShort(getContext(), "错误码 ：" + code + "\n" + aMapLocation.getLocationDetail());
        }
    }

    /******************************** 控件的基本点击事件监听 *******************************/

    @OnClick({R.id.iv_site_pick,
            R.id.tv_site_down,
            R.id.btn_refresh ,
            R.id.titlebar_left_menu ,
            R.id.station_nation,
            R.id.station_pollution,
            R.id.station_all,
            R.id.station_micro})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            // 展开站点类型
            case R.id.iv_site_pick:
                showSiteTypeUI();
                break;
            //收起站点类型
            case R.id.tv_site_down:
                hideSiteTypeUI();
                break;
            //刷新
            case R.id.btn_refresh:
                isRefresh = true;
                if(data_type==DATA_STATION) {
                    getStationData();
                }else {
                    getPsonLocationData();
                }
                break;
            //展示抽屉布局
            case R.id.titlebar_left_menu:
                if (listener != null) {
                    listener.onShowDrawerBtnClick();
                }
                break;
            //切换站点类型
            case R.id.station_all:
                changeStationMarker(StatusConst.STATION_ALL);
                break;
            case R.id.station_micro:
                changeStationMarker(StatusConst.STATION_MICRO);
                break;
            case R.id.station_nation:
                changeStationMarker(StatusConst.STATION_NATION);
                break;
            case R.id.station_pollution :
                changeStationMarker(StatusConst.STATION_POLLUTION);
                break;

        }
    }

    /**
     * segment 切换监听
     */
    private RadioGroup.OnCheckedChangeListener checkedChangedListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
            //切换地图类型  和 标记点弹窗的透明度
            switch (checkedId) {
                case R.id.rb_normal:
                    mapType = AMap.MAP_TYPE_NORMAL;
                    windowAlpha = WINDOW_ALPHA_WHITE;
                    if(data_type == DATA_USER){//从人员状态切换回站点状态
                        data_type = DATA_STATION ;
                        isDoAnim = true;
                        showStationDataUI();
                        LabelUIControl(true);
                        getStationData();
                    }else {
                        //图例UI控制
                        if (!isDoAnim) {
                            LabelUIControl(true);
                            isDoAnim = true;
                            changeMarkerType();
                        }
                    }
                    break;
                case R.id.rb_night:
                    mapType = AMap.MAP_TYPE_NIGHT;
                    windowAlpha = WINDOW_ALPHA_NIGHT;
                    if(data_type == DATA_USER){ //从人员状态切换回站点状态
                        data_type = DATA_STATION ;
                        isDoAnim = false;
                        showStationDataUI();
                        getStationData();
                    }else {
                        //图例UI控制
                        if (isDoAnim) {
                            LabelUIControl(false);
                            isDoAnim = false;
                            changeMarkerType();
                        }
                    }
                    break;
                case R.id.rb_satellite:
                    windowAlpha = WINDOW_ALPHA_WHITE;
                    mapType = AMap.MAP_TYPE_SATELLITE;
                    if(data_type == DATA_USER){//从人员状态切换回站点状态
                        data_type = DATA_STATION ;
                        isDoAnim = true;
                        showStationDataUI();
                        LabelUIControl(true);
                        getStationData();
                    }else {
                        //图例UI控制
                        if (!isDoAnim) {
                            LabelUIControl(true);
                            isDoAnim = true;
                            changeMarkerType();
                        }
                    }
                    break;
                case R.id.rb_person:
                    if(data_type == DATA_STATION){
                        data_type = DATA_USER;
                        mapType = AMap.MAP_TYPE_NORMAL;
                        windowAlpha = WINDOW_ALPHA_WHITE;
                        hideStationDataUI();
                        if (isDoAnim) {
                            LabelUIControl(false);
                        }
                        getPsonLocationData();
                    }
                    break;
            }
            aMap.setMapType(mapType);
            if (infoWindow != null) {
                infoWindow.setAlpha(windowAlpha);
            }
        }
    };

    /**
     * 图例（常规/直观）切换
     */
    private RadioGroup.OnCheckedChangeListener markerChangerListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
            switch (checkedId) {
                case R.id.rb_marker_cg:
                    label_type = LABEL_CG;
                    break;
                case R.id.rb_marker_zg:
                    label_type = LABEL_ZG;
                    break;
            }
            changeMarkerType();
        }
    };

    /**
     * 切换因子
     */
    private HorizontalSelectScrollView.FactorChangerListener factorChangerListener = new HorizontalSelectScrollView.FactorChangerListener() {
        @Override
        public void onChangeListener(String factor) {
            factor_type = AirLevelUtil.getType(factor);
            changeMarkerType();
        }
    };

    /**
     * 切换当前显示因子
     */
    private void changeMarkerType() {
        if (aMap != null) {
            aMap.clear();
            markerList.clear();
        }
        for (AirStationE e : siteList) {
            addStationMarker(e);
        }
    }

    /******************************** UI交互 *******************************/
    /**
     * 图例UI控制
     */
    private void LabelUIControl(boolean isVisible) {
        initHideAlphaAnim();
        initShowAlphaAnim();
        if (isVisible) {
            ivMarkerLabel.startAnimation(showAlphaAnim);
            ivMarkerLabel.setVisibility(View.VISIBLE);
            rgMarkerType.startAnimation(showAlphaAnim);
            rgMarkerType.setVisibility(View.VISIBLE);
        } else {
            ivMarkerLabel.startAnimation(hideAlphaAnim);
            ivMarkerLabel.setVisibility(View.GONE);
            rgMarkerType.startAnimation(hideAlphaAnim);
            rgMarkerType.setVisibility(View.GONE);
        }
    }

    /**
     * 显示站点分类
     */
    private void showSiteTypeUI(){
        initHideAlphaAnim();
        initShowTransAnim();
        ivSitePick.startAnimation(hideAlphaAnim);
        ivSitePick.setVisibility(View.GONE);
        layoutSiteType.startAnimation(showTransAnim);
        layoutSiteType.setVisibility(View.VISIBLE);
    }

    /**
     * 隐藏站点分类
     */
    private void hideSiteTypeUI(){
        initShowAlphaAnim();
        initHideTansAnim();
        ivSitePick.startAnimation(showAlphaAnim);
        ivSitePick.setVisibility(View.VISIBLE);
        layoutSiteType.startAnimation(hideTransAnim);
        layoutSiteType.setVisibility(View.GONE);
    }

    /**
     * 切换站点类型显示分类
     * @param type
     */
    private void changeStationMarker(int type){
        for (Marker marker: markerList){
            if(type==StatusConst.STATION_ALL){
                marker.setVisible(true);
            }else {
                AirStationE stationE = (AirStationE) marker.getObject();
                if(stationE.getStationType()== type){
                    marker.setVisible(true);
                }else {
                    marker.setVisible(false);
                }
            }
        }
    }

    private void hideStationDataUI(){
        initHideAlphaAnim();
        svFactor.startAnimation(hideAlphaAnim);
        svFactor.setVisibility(View.GONE);
        frameLayout.startAnimation(hideAlphaAnim);
        frameLayout.setVisibility(View.GONE);
    }
    private void showStationDataUI(){
        initShowAlphaAnim();
        svFactor.startAnimation(showAlphaAnim);
        svFactor.setVisibility(View.VISIBLE);
        frameLayout.startAnimation(showAlphaAnim);
        frameLayout.setVisibility(View.VISIBLE);
    }

    /********************************初始化动画效果*******************************/

    private void initHideAlphaAnim(){
        if (null == hideAlphaAnim) {
            hideAlphaAnim = new AlphaAnimation(1f, 0f);
            hideAlphaAnim.setDuration(300);
        }
    }
    private void initShowAlphaAnim(){
        if (null == showAlphaAnim) {
            showAlphaAnim = new AlphaAnimation(0f, 1f);
            showAlphaAnim.setDuration(300);
        }
    }
    private void initHideTansAnim(){
        if(null == hideTransAnim){
            hideTransAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
                    0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                    -1.0f);
            hideTransAnim.setDuration(300);
        }
    }
    private void initShowTransAnim(){
        if(null == showTransAnim){
            showTransAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                    -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
            showTransAnim.setDuration(300);
        }
    }

    private void initMarkerAnim(){
         animationSet = new AnimationSet(true);
        animationSet.addAnimation(new ScaleAnimation(0,1,0,1));
        animationSet.addAnimation(new com.amap.api.maps.model.animation.AlphaAnimation(0,1));
        animationSet.setInterpolator(new LinearInterpolator());
        //整个移动所需要的时间
        animationSet.setDuration(1000);
    }

    /********************************初始化marker标记点*******************************/
    /**
     * 添加站点Marker
     * 返回一个经纬度对象
     *
     * @param stationE
     */

    @SuppressLint("NewApi")
    private LatLng addStationMarker(AirStationE stationE) {

        // 经纬度
        Marker marker= null;
        LatLng latLng = new LatLng(stationE.getLat(), stationE.getLnt());
        MarkerOptions markerOptions = new MarkerOptions().anchor(0.5f, 1)
                .title("") .position(latLng);
        AirStationE.AirLevel airLevel = AirLevelUtil.getAirLevelObj(factor_type,getTypeValue(factor_type,stationE) , stationE.isOnline());
        stationE.setAirLevel(airLevel);

        //夜景
        if(mapType == AMap.MAP_TYPE_NIGHT){
            View view = View.inflate(getActivity(), R.layout.layout_marker_night, null);
            FrameLayout layout = (FrameLayout) view.findViewById(R.id.ly_marker_night);
            TextView airValue = (TextView) view.findViewById(R.id.air_value);
            stationE.setValue(getTypeValue(factor_type, stationE));
            // 设置显示
            layout.setBackground(ContextCompat.getDrawable(getContext(), airLevel.getNightResId()));
            airValue.setText("" + stationE.getValue());
            markerOptions.icon(BitmapDescriptorFactory.fromView(view));
        }else {
            //常规
            if (label_type == LABEL_CG) {
                markerOptions.icon(BitmapDescriptorFactory.fromResource(AirLevelUtil.getLabelIcon(stationE.getStationType(), airLevel.getLevel())));
            }
            //直观
            if (label_type == LABEL_ZG) {
                View view = View.inflate(getActivity(), R.layout.layout_marker_air, null);
                FrameLayout layout = (FrameLayout) view.findViewById(R.id.ly_marker_air);
                TextView airValue = (TextView) view.findViewById(R.id.air_value);
                stationE.setValue(getTypeValue(factor_type, stationE));
                System.out.println(factor_type);
                System.out.println(stationE.getValue());
                // 设置显示
                layout.setBackground(ContextCompat.getDrawable(getContext(), airLevel.getMarkerResId()));
                if(factor_type == StatusConst.AIR_TYPE_AQI){
                    airValue.setText("" + (int)stationE.getValue());
                } else {
                    airValue.setText("" + stationE.getValue());
                }
                markerOptions.icon(BitmapDescriptorFactory.fromView(view));
            }
        }
        //添加标记点
        marker = aMap.addMarker(markerOptions);
        marker.setObject(stationE);
        markerList.add(marker);
        // 条件判断
        if (mnStr.length() > 0 && stationE.getMn().equals(mnStr)) {
            marker.showInfoWindow();
            aMap.animateCamera(
                    CameraUpdateFactory.changeLatLng(new LatLng(stationE.getLat(), stationE.getLnt())));
        }
        //动画
        if(animationSet == null){
            initMarkerAnim();
        }
        marker.setAnimation(animationSet);
        marker.startAnimation();
        return latLng;
    }

    /**
     * 添加人员标记点
     * @param userE
     */
    private LatLng addPsonMarker(UserE userE) {
        LatLng latLng = new LatLng(userE.getLat(),userE.getLnt());

        Marker marker = aMap.addMarker(new MarkerOptions().position(latLng)
                .title("")
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.mail_40)));
        marker.setObject(userE);
        AmapUtil.startGrowAnimation(marker);
        return latLng;
    }

    /********************************工具类方法*******************************/
    /**
     * 获取对应因子数值
     *
     * @param type
     * @param e
     * @return
     */
    private double getTypeValue(int type, AirStationE e) {
        switch (type) {
            case StatusConst.AIR_TYPE_AQI:
                return e.getAQI();
            case StatusConst.AIR_TYPE_CO:
                return e.getCO();
            case StatusConst.AIR_TYPE_NO2:
                return e.getNO2();
            case StatusConst.AIR_TYPE_O3:
                return e.getO3();
            case StatusConst.AIR_TYPE_PM10:
                return e.getPM10();
            case StatusConst.AIR_TYPE_PM25:
                return e.getPM25();
            case StatusConst.AIR_TYPE_SO2:
                return e.getSO2();
            case StatusConst.AIR_TYPE_VOC:
                return e.getVOC();
            default:
                return e.getAQI();
        }
    }


}
